<?php
// +----------------------------------------------------------------------
// | ThinkSNS
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.thinksns.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: nonant <nonant@thinksns.com>
// +----------------------------------------------------------------------
//

class MessageAction extends Action{
	
	function _initialize(){
		$this->setTitle( L('index') );
	}	
	
	//收件箱
	function index(){
		$type=($_GET['type'])?$_GET['type']:'inceptbox';
		$this->$type();
	}

	function inceptbox(){
        //查询
        $dao = D("Message");
        $map["toUserId"] = $this->mid;
        $map["is_new"] = 1;
		$map["is_del"] = array("NEQ",$this->mid);

        $msgs = $dao->where($map)->order("cTime desc")->findPage(5);

        $this->assign("list",$msgs["data"]);
        $this->assign("page",$msgs["html"]);
		$this->display('inceptbox');
	}

	function sendbox(){
        $dao = D("Message");
        $map["fromUserId"] = $this->mid;
        $map["is_new"] = 1;
		$map["is_del"] = array("NEQ",$this->mid);

        $msgs = $dao->where($map)->order("cTime desc")->findPage(5);
        $this->assign( 'count',$dao->where( $map )->count() );
        //echo $dao->getLastSql();
        //dump($msgs);
        $this->assign("list",$msgs["data"]);
        $this->assign("page",$msgs["html"]);
		$this->display('sendbox');
	}

	function send(){
		if($_GET['touid']){
			$info = D('User')->where('uid='.intval($_GET['touid']))->find();
			if($info['uid']){
				if($info['uid']!=$this->mid){
					$this->assign('touid',$info['uid']);
				}else{
					$this->error(L('no_mail_to_self'));
				}
			}else{
				$this->error(L('user_unavailable'));
				exit;
			}
		}
		$this->display('send');
	}

	function view(){
        $id = intval($_GET["id"]);

        $dao = D("Message");

        //主信息
        $map["id"] = $id;
        $msg = $dao->where($map)->find();
        $this->assign("msg",$msg);
        if($_GET["t"] == "inbox"){
            $sql = "UPDATE __TABLE__ SET is_read = 1 WHERE id = ".$id;
            $dao->query($sql);
        }
        //回复
        $map_r["replyMsgId"] = $id;
        $r_msgs = $dao->where($map_r)->findAll();
        $this->assign("r_msgs",$r_msgs);
        if($_GET["t"] == "inbox"){
            $sql = "UPDATE __TABLE__ SET is_read = 1 WHERE replyMsgId = ".$id." AND fromUserId != ".$this->mid;
            $dao->query($sql);
        }

        $lid = $_GET["lid"]?$_GET["lid"]:"reply";
        $this->assign("lid",$lid);
        $this->display('view');;
	}

	function dosendmessage(){
        $toUserIds = explode(",",$_POST["sendto_uids"]);
        //unset($_POST["fri_ids"]);
		$_POST['subject'] = t($_POST['subject']);
		$_POST['content'] = t($_POST['content']);
        $dao = D("Message");

		$r = $dao->create();
		if(false === $r) $this->error($dao->getError());

        $dao->cTime = time();
        $dao->fromUserId = $this->mid;
        $server = x('Notify');
        foreach($toUserIds as $uid){
            $dao->toUserId = $uid;
            $r = $dao->add();
            if($r){
            	$title['title'] = $_POST['subject'];
            	$body['content'] = $_POST['content'];
            	$server->put('home_sendmessage',$uid,$title,$body);
            }
        }

        $this->assign('jumpUrl','index.php?mod=message&&act=sendbox');
       $this->success(L('send_success'));
	}

	function doreply(){
   		$content = trim(t($_POST["content"]));
		if(empty($content)){
			$this->error(L('no_empty_content'));
		}
        $replyMsgId = intval($_POST["replyMsgId"]);
        if(0 == $replyMsgId){
        	$this->error(L('error_msg_id'));
        }

        $type = $_POST["type"];
        unset($_POST["type"]);

        $dao = D("Message");

        //先把这个会话与自己有关的msg的is_new设为0
        $sql1 = "UPDATE __TABLE__ SET `is_new`=0 WHERE fromUserId = ".$this->mid." AND id = ".$replyMsgId;
        $dao->query($sql1);
        $sql2 = "UPDATE __TABLE__ SET `is_new`=0 WHERE fromUserId = ".$this->mid." AND replyMsgId = ".$replyMsgId;
        $dao->query($sql2);


        //算出回复给谁
        $main_msg = $dao->field("fromUserId,toUserId")->find($replyMsgId);
        if($main_msg["fromUserId"] == $this->mid){
            $toUserId = $main_msg["toUserId"];
        }else{
            $toUserId = $main_msg["fromUserId"];
        }


        //然后新建一条
        $dao->create();
        $dao->subject = L('reply') . "：".$_POST["subject"];
        $dao->fromUserId = $this->mid;
        $dao->toUserId = $toUserId;
        $dao->cTime   = time();
		$dao->is_read = 0;

        $dao->replyMsgId = $_POST["replyMsgId"];
        $dao->content = t($_POST["content"]);


        $dao->add();

        $url = __APP__."&mod=message&act=view&type=$type&id=$replyMsgId#reply";
        $this->redirect($url);
	}

	function notify(){
		//$time = getdate(time());
		$_GET['t'] = in_array($_GET['t'],array('isread','unread'))?$_GET['t']:'unread';
		if($_GET['t']=='unread'){
			$map['isread'] = 0;
			$page = '';
		}else{
			$map['isread'] = 1;
			$page = 10;
		}
//		if($_GET['d']=='today'){
//			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],$time['mday'],$time['year']));
//		}elseif ($_GET['d']=='weekday'){
//			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],$time['mday']-7,$time['year']));
//		}elseif ($_GET['d']=='month'){
//			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],1,$time['year']));
//		}else{
//			$map['isread'] = 0;
//		}
		$map['touid'] = $this->mid;
		$notify = x('Notify')->get($map,$page);
		if($_GET['t']=='unread'){
			//if($notify['count']==0){
			//	redirect(__URL__.'&mod=message&act=index&type=notify&t=isread');
			//}else{
				foreach ($notify['data'] as $key=>$val){
					$ids[] = $val['id'];
				}
				$setMap['id'] = array('in',$ids);
				M('Notify')->where($setMap)->setField('isread',1);
			//}
		}

		$this->assign('t',$_GET['t']);
		$this->assign('notify',$notify);
		$this->display('notify');
	}

	function setnotify(){
		$intId = intval($_POST['id']);
		switch ($_POST['type']){
			case 'dodel':
				echo M('Notify')->where("id=$intId AND touid=".$this->mid)->delete();
			break;

			case 'setread':
				echo M('Notify')->setField('isread',1,"id=$intId AND touid=".$this->mid);
			break;
		}

	}

	function wall(){
		$dao = D('Wall','space');
		
		$time = getdate(time());
		if($_GET['d']=='today'){
			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],$time['mday'],$time['year']));
		}elseif ($_GET['d']=='weekday'){
			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],$time['mday']-7,$time['year']));
		}elseif ($_GET['d']=='month'){
			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],1,$time['year']));
		}
		
		
		$map['uid'] = $this->mid;
		$map['fid'] = 0;
		$list = $dao->where($map)->order('id DESC')->findpage(10);
		foreach ($list['data'] as $key=>$val){
			if(0!=$dao->where("fid=$val[id]")->count()){
				$list['data'][$key]['reply'] = $dao->where("fid=$val[id]")->order('id ASC')->findall();
			}
		}		
		$this->assign($list);
		$this->display('wall');
	}
	
	function feed(){
		$strType = ($_GET['type'])?$_GET['type']:'attention';
		$intFid  = intval( $_GET['fid'] );
		$time = getdate(time());
		if($_GET['d']=='today'){
			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],$time['mday'],$time['year']));
		}elseif ($_GET['d']=='weekday'){
			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],$time['mday']-7,$time['year']));
		}elseif ($_GET['d']=='month'){
			$map['cTime'] = array('gt',mktime(0,0,0,$time['mon'],1,$time['year']));
		}

		$space['group'] = D('Group','group')->getUserJoinList($this->mid);
		
		if($strType=='attention'){
			$map['uid'] = array('in',x('Follow')->getFollowData($this->mid,'user'));
			$map['display'] = 0;
		}elseif ($strType=='group'){
			$map['appname'] = 'group';
			if( $intFid && in_array( $intFid,$space['group']['gids'] ) ){
				$map['fid']     = $intFid;
			}else{
				$map['fid']     = array('IN',$space['group']['gids']);
			}
		}else{
			$map['display'] = 0;
		}
		//$map['type'] = 'space_record';
		$space['feeds']            = X('Feed')->get($map,10,true,0,false,false);
		$this->assign('space',$space);
		$this->assign('type',$strType);
		$this->assign('d',$_GET['d']);
		$this->display();
	}

	/*
	 * 删除某条消息
	 *
	 */
	function delMsg() {

		$id = intval($_POST["id"]);

		$dao = D('Message');

		$map["toUserId"] =	$this->mid; //为了safe
		$map["id"]       =	$id;

		$map = "(toUserId = ".$this->mid." OR fromUserId = ".$this->mid.") AND id = ".$id;

		$msg = $dao->where($map)->find();

		if($msg){
			if($msg["is_del"] == 0){
				$dao->is_del = $this->mid;	//如果对方没有删除过
				echo $dao->save();
			}else{
				$dao->is_new = 0;			//如果对方删除过
				echo $dao->save();
			}
		}

	}


	/*
	 * 删除某些消息
	 *
	 */
	function delSomeMsg() {

		if(!$_POST["ids"]) return;

		$ids = explode(",",$_POST["ids"]);;

		$dao = D('Message');

		foreach($ids as $id){

			$map = "(toUserId = ".$this->mid." OR fromUserId = ".$this->mid.") AND id = ".$id;

			$msg = $dao->where($map)->find();

			if($msg){
				if($msg["is_del"] == 0){
					$dao->is_del = $this->mid;	//如果对方没有删除过
					echo $dao->save();
				}else{
					$dao->is_new = 0;			//如果对方删除过
					echo $dao->save();
				}
			}
		}

		echo 1;

	}

	/*
	 * 标记已读 -- 某条消息
	 *
	 */
	function bjReadMsg() {

		$id		 = intval($_POST["id"]);
		$is_read = intval($_POST["is_read"]);

		$dao = D('Message');

		$map["toUserId"] =	$this->mid; //为了safe
		$map["id"]       =	$id;

		$msg = $dao->where($map)->find();
		if($msg){
			$dao->is_read = $is_read;
			$dao->save();
		}
	}


	/*
	 * 标记已读 -- 某些消息
	 *
	 */
	function bjReadSomeMsg() {

		if(!$_POST["ids"]) return;
		$is_read = intval($_POST["is_read"]);

		$ids = explode(",",$_POST["ids"]);;

		$dao = D('Message');

		foreach($ids as $id){

			$map["toUserId"] =	$this->mid; //为了safe
			$map["id"]       =	$id;

			$msg = $dao->where($map)->find();
			if($msg){
				$dao->is_read = $is_read;
				$dao->save();
			}
		}

		echo 1;

	}

	protected function getUserId($uname){
		$info = M('User')->where("uname='$uname'")->field('uid')->find();
		if($info){
			return $info['uid'];
		}
	}
}
?>